package cn.tedu._04weibo.controller;

import cn.tedu._04weibo.base.response.JsonResult;
import cn.tedu._04weibo.base.response.StatusCode;
import cn.tedu._04weibo.mapper.UserMapper;
import cn.tedu._04weibo.pojo.dto.UserLoginParam;
import cn.tedu._04weibo.pojo.dto.UserRegParam;
import cn.tedu._04weibo.pojo.entity.User;
import cn.tedu._04weibo.pojo.vo.UserLoginVo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Slf4j
@RestController
@Tag(name = "_01用户模块")
@RequestMapping("/v1/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/reg")
    @Operation(summary = "用户注册")
    @ApiOperationSupport(order = 10)
    public JsonResult reg(@RequestBody @Validated UserRegParam param) {
        log.info("注册用户,参数:{}",param);

        String name = param.getUsername();

        int rows = userMapper.selectByName(name);

        if (rows > 0) {
            return new JsonResult(StatusCode.USERNAME_EXIST);
        }

        User user = new User();

        BeanUtils.copyProperties(param, user);
        user.setCreateTime(new Date());

        int i = userMapper.insert(user);
        if (i > 0) {
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    @ApiOperationSupport(order = 20)
    public JsonResult login(@RequestBody UserLoginParam param, HttpSession session) {
        log.info("登录用户,参数:{}",param);
        UserLoginVo userLoginVo = userMapper.selectByNameAndPassword(param);

        session.setAttribute("user", userLoginVo);

        if (userLoginVo != null) {
            return JsonResult.ok(userLoginVo);
        }

        return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
    }

    @GetMapping("currentUser")
    @Operation(summary = "获取当前登录用户")
    @ApiOperationSupport(order = 30)
    public JsonResult currentUser(HttpSession session) {
        UserLoginVo user = (UserLoginVo) session.getAttribute("user");
        if (user != null) {
            return JsonResult.ok(user);
        }
        return new JsonResult(StatusCode.NOT_LOGIN);
    }

}
